package actions.runnable;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import actions.JobTimer;

import objects.MessageCodes;
import objects.data.Message;
import objects.data.WorkPacket;


import ssh.SSHUtils;
import utils.Shell;
import utils.Utils;
import utils.ZipUtils;


public class JobMonitor extends Thread implements MessageCodes {
	public WorkPacket workPacket;
	public JobTimer timerJob;
	public String jobid = null;

	public JobMonitor(WorkPacket wp, JobTimer t) {
		this.workPacket = wp;
		this.timerJob = t;
	}

	public void run() {
		boolean queued = false;
		boolean running = false;
		try {

			while (true) {
				String s = null;
				String cmdd = "qstat | grep " + System.getProperty("user.name")
						+ " | grep " + workPacket.uniqueId + " | awk '{print($5)}'";
				if ((s = Shell.runCmd(cmdd)) != null) {
					// Utils.out("OUT WAS "+s);
					switch (s.charAt(0)) {

					case 'Q':
						if (!queued) {
							Utils.ws.send(new Message(JOB_QUEUED, workPacket.uniqueId));
							String cmd = "qstat | grep " + System.getProperty("user.name")
									+ " | grep " + workPacket.uniqueId + " | awk '{print($1)}'";
							jobid =  Shell.runCmd(cmd).replace(".master", "");
							Utils.jobs.put(workPacket.uniqueId,this);
							queued = true;
						}
						break;
					case 'R':
						if (!running) {
							Utils.ws.send(new Message(JOB_EXECUTING, workPacket.uniqueId));
							timerJob.endQueued();
							running = true;
						}
						break;
					}
				} else
					break;

				// TODO sleep according to walltime
				if (running)
					Thread.sleep(10000);
				else
					Thread.sleep(2000);
			}
			Utils.jobs.remove(workPacket.uniqueId);
			Utils.out("+ job terminated: " + workPacket.jobname);
			Utils.out("+ zipping file " + workPacket.jobname);
			String outfile = workPacket.jobname + "_results.zip";
			
			ZipUtils.zip(workPacket.uniqueId, outfile);
			
			Utils.out("+ sftp: uploading file" + outfile);
			
			if (!SSHUtils.ScpTo(new File(outfile).getPath(), "~/" + workPacket.uniqueId
					+ "/" + outfile)) {
				Utils.out("FAILED SENDING FILE " + workPacket.uniqueId);
				Utils.ws.send(new Message(JOB_FAILED, workPacket.uniqueId));
				return;
			}
			
			Utils.out("+ cleaning up...");
			
			new File(outfile).delete();
			Utils.removeDirectory(new File(workPacket.uniqueId));
			
			Utils.out("+ terminating job monitor thread");
			Utils.ws.send(new Message(JOB_TERMINATED, workPacket.uniqueId));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
